package com.shu.io;

import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2020/4/15 18:14
 */
@Slf4j
@Accessors(chain = true)
@Data
public class Person implements Serializable, Cloneable {
    private static final long serialVersionUID = -3116169725642569977L;

    private String name;
    private int age;
    private Person son;

    /**
     * 默认浅克隆
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    public Person clone() throws CloneNotSupportedException {
        return (Person) super.clone();
    }


    /**
     * 深度克隆方法一:利用clone()
     * @return
     * @throws CloneNotSupportedException
     */
    public Person deepClone() throws CloneNotSupportedException {
        Person result = (Person) super.clone();
        if (son != null) {
            result.son = (Person) son.clone();
        }
        return result;
    }


    /**
     * 深度克隆方法一:IO流克隆
     *
     * @return
     */
    public Person IOClone() {
        try {
            // 序列化
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bos);
            os.writeObject(this);

            // 反序列化
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream is = new ObjectInputStream(bis);
            return (Person) is.readObject();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

}
